<template>
  <div class="pt-3 relative">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <!-- <el-form-item label="所属行业" prop="industryId">
        <el-input
          v-model="queryParams.industryId"
          placeholder="请输入所属行业"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="catId">
        <el-input
          v-model="queryParams.catId"
          placeholder="请输入所属分类"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="文件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="文件路径" prop="path">
        <el-input
          v-model="queryParams.path"
          placeholder="请输入文件路径"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序字段" prop="sortValue">
        <el-input
          v-model="queryParams.sortValue"
          placeholder="请输入排序字段"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8 absolute right-6 top-4" v-if="cateKb?.id">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['web:lm:kb:sdkLmKbFile:add']"
        >
          上传文件
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="handleTagClick"> 标签管理 </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate({})"
          v-hasPermi="['web:lm:kb:sdkLmKbFile:edit']"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete({})"
          v-hasPermi="['web:lm:kb:sdkLmKbFile:remove']"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['web:lm:kb:sdkLmKbFile:import']"
        >
          导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['web:lm:kb:sdkLmKbFile:export']"
        >
          导出
        </el-button>
      </el-col>-->
      <!-- <right-toolbar v-model:showSearch="showSearch" @query-table="getList" /> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      @cell-dblclick="handleCellDblclick"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件名称" align="center" prop="name" />
      <el-table-column label="文件md5" align="center" prop="md5" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="版本号" align="center" prop="version" />
      <el-table-column label="分片方式" align="center" prop="chunkType" />
      <el-table-column label="智库文本路径" align="center" prop="fileTextPath">
        <template #default="{ row }">
          <div class="texthoveColor">{{ row.fileTextPath }}</div>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center">
        <template #default="{ row }">
          <div v-if="row.sdkLmKbFileTags?.length" class="flex justify-center gap-0.5">
            <el-tag v-for="(tag, index) in row.sdkLmKbFileTags" :key="index" type="primary">
              {{ tag.name }}
            </el-tag>
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="文件类型" align="center" prop="fileType" /> -->
      <!-- <el-table-column label="智库类型" align="center" prop="type" /> -->
      <!-- <el-table-column label="文件路径" align="center" prop="path" /> -->
      <!-- <el-table-column label="是否删除" align="center" prop="del" /> -->
      <!-- <el-table-column label="排序字段" align="center" prop="sortValue" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['web:lm:kb:sdkLmKbFile:edit']"
          >
            修改
          </el-button>
          <el-button
            link
            type="primary"
            icon="Download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['web:lm:kb:sdkLmKbFile:remove']"
          >
            下载
          </el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            style="color: red"
            v-hasPermi="['web:lm:kb:sdkLmKbFile:remove']"
          >
            删除
          </el-button>
          <el-button
            link
            type="primary"
            icon="ScaleToOriginal"
            @click="handleFragment(scope.row)"
            v-hasPermi="['web:lm:kb:sdkLmKbFile:remove']"
          >
            分片管理
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="pageParams.pageNum"
      v-model:limit="pageParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="txtDailogInfo.title"
      v-model="txtDailogInfo.visible"
      :width="txtDailogInfo.width"
      append-to-body
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <!--  <div class="text-base" v-html="setHtmlMarked(txtDailogInfo.data)"></div>  -->
      <MarkDown
        v-if="txtDailogInfo.type === 'filePreview'"
        v-model:value="txtDailogInfo.data"
        :height="730"
      />

      <SdkLmKbShard
        v-else-if="txtDailogInfo.type === 'shard'"
        :params="shardParams"
        :commonIdsParams="commonIdsParams"
      />

      <template #footer>
        <div v-if="txtDailogInfo.type === 'filePreview'" class="dialog-footer">
          <el-button type="primary">保存</el-button>
          <el-button @click="txtDailogInfo.visible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属智库">
          <el-input v-model="cateKb.name" disabled placeholder="请输入所属智库" />
        </el-form-item>
        <el-form-item label="上传文件" prop="path">
          <FileUpload
            v-model="form.path"
            :limit="1"
            :isShowTip="false"
            @success="handleSetFileInfo"
          />
        </el-form-item>

        <el-form-item label="文件名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="分片方式" prop="chunkType">
          <el-select v-model="form.chunkType" placeholder="请选择">
            <el-option label="自动" value="自动" />
            <el-option label="手动" value="手动" />
          </el-select>
        </el-form-item>

        <el-form-item label="智库类型" prop="type">
          <el-input v-model="form.type" placeholder="请输入智库类型" />
        </el-form-item>
        <el-form-item label="排序字段" prop="sortValue">
          <el-input-number
            v-model="form.sortValue"
            style="width: 300px"
            placeholder="请输入排序字段"
          />
        </el-form-item>

        <el-form-item label="标签" prop="sdkLmKbFileTags">
          <el-input
            v-model="sdkLmKbFileTagVal"
            placeholder="请输入按回车新增标签"
            clearable
            @keyup.enter="handleAddLabel"
          />
          <div class="flex flex-wrap gap-2 mt-2">
            <el-tag
              v-for="(item, index) in form.sdkLmKbFileTags"
              closable
              @close="handleDeleteLabel(item, index)"
              :key="item.name + index"
            >
              {{ item.name }}
            </el-tag>
          </div>
        </el-form-item>
        <!--  <el-form-item label="是否删除" prop="del">
          <el-radio-group v-model="form.del">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序字段" prop="sortValue">
          <el-input v-model="form.sortValue" placeholder="请输入排序字段" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的知识库文件数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import {
    addSdkLmKbFile,
    delSdkLmKbFile,
    downloadSdkLmKbFile,
    getSdkLmKbFileInfo,
    pageSdkLmKbFile,
    tplSdkLmKbFile,
    updateSdkLmKbFile,
  } from '@/api/intelligencebase/sdkLmKbFile';
  import { getToken } from '@/utils/auth';
  import axios from 'axios';
  import DOMPurify from 'dompurify';
  import { marked } from 'marked';
  import { computed, ref, watch } from 'vue';
  // import { parseTime, addFieldTimeRange, addFieldDateRange } from '@/utils/base';
  // import { useDict, useConstDict } from '@/utils/dict';
  import { MarkDown } from '@/components/Markdown';
  import modal from '@/plugins/modal';
  import SdkLmKbShard from './sdkLmKbShard.vue';

  // const {} = useDict();

  const props = defineProps({
    cateKb: {
      type: Object,
      default: () => ({}),
    },
  });

  const pageParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const queryParams = ref({
    industryId: null,
    catId: null,
    kbId: null,
    name: null,
    fileType: null,
    type: null,
    path: null,
    del: null,
    sortValue: null,
  });
  const shardParams = ref({
    knowledgeType: 'file',
    sourceId: null,
  });
  const queryRef = ref(null);
  const list = ref([]);
  const open = ref(false);
  const loading = ref(false);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref('');
  const sdkLmKbFileTagVal = ref('');

  const uploadRef = ref(null);
  const upload = ref({
    open: false,
    title: '',
    isUploading: false,
    updateSupport: 0,
    headers: { Authorization: 'Bearer ' + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + '/web/lm/kb/sdkLmKbFile/import',
  });

  const formRef = ref(null);
  const form = ref({});
  const rules = ref({
    id: [
      {
        required: true,
        message: '主键不能为空',
        trigger: 'blur',
      },
    ],
    name: [
      { required: true, message: '文件名不能为空' },
      {
        min: 0,
        max: 64,
        message: '名称长度必须介于 0 和 64 之间',
        trigger: 'blur',
      },
    ],
    fileType: [
      {
        min: 0,
        max: 64,
        message: '文件类型长度必须介于 0 和 64 之间',
        trigger: 'change',
      },
    ],
    type: [
      {
        min: 0,
        max: 64,
        message: '智库类型长度必须介于 0 和 64 之间',
        trigger: 'change',
      },
    ],
    path: [
      { required: true, message: '请上传文件' },
      {
        min: 0,
        max: 255,
        message: '文件路径长度必须介于 0 和 255 之间',
        trigger: 'blur',
      },
    ],
  });

  const txtDailogInfo = ref({
    visible: false,
    title: '文本预览',
    data: '',
    type: '',
    width: '700px',
  });

  const cateKb = computed(() => {
    return props.cateKb;
  });
  const commonIdsParams = computed(() => {
    return {
      industryId: cateKb.value.industryId,
      catId: cateKb.value.catId,
      kbId: cateKb.value.id,
    };
  });

  watch(
    () => props.cateKb,
    (val) => {
      if (!val?.id) {
        list.value = [];
        total.value = 0;
        pageParams.value.pageNum = 1;
        return;
      }
      //  industryId: null,
      // catId: null,
      // kbId: null,
      queryParams.value.kbId = val.id;
      getList();
    },
  );

  function getList() {
    loading.value = true;
    pageSdkLmKbFile(pageParams.value, queryParams.value)
      .then((res) => {
        list.value = res?.data?.records ?? [];
        total.value = res?.data?.total ?? 0;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  // 双击文本路径----预览文本
  function handleCellDblclick(row, column) {
    console.log({ row, column });
    if (column.property === 'fileTextPath') {
      const url = import.meta.env.VITE_APP_BASE_API + row[column.property];
      if (!url) return;
      axios
        .get(url, {
          responseType: 'text',
          headers: {
            Authorization: 'Bearer ' + getToken(),
          },
        })
        .then((res) => {
          console.log(res);
          txtDailogInfo.value.data = res.data;
          txtDailogInfo.value.visible = true;
          txtDailogInfo.value.title = '文本内容';
          txtDailogInfo.value.type = 'filePreview';
          txtDailogInfo.value.width = '1500px';
        });
    }
  }

  // 切片管理按钮
  function handleFragment(row) {
    shardParams.value.sourceId = row.id;
    txtDailogInfo.value.type = 'shard';
    txtDailogInfo.value.width = '1500px';
    txtDailogInfo.value.title = '切片管理列表';
    txtDailogInfo.value.visible = true;
  }

  // md设置html内容
  // eslint-disable-next-line
  function setHtmlMarked(content) {
    return DOMPurify.sanitize(marked(content));
  }

  function cancel() {
    open.value = false;
    reset();
  }

  // 标签 新增 事件
  function handleAddLabel() {
    const tagV = sdkLmKbFileTagVal.value?.trim();
    if (!tagV) {
      modal.msgWarning('请输入标签名');
      return;
    }
    form.value.sdkLmKbFileTags.push({ name: tagV });
    sdkLmKbFileTagVal.value = '';
  }

  // 标签 删除事件
  function handleDeleteLabel(row) {
    const findIndex = form.value.sdkLmKbFileTags.findIndex((item) => {
      if (item.id && item.id === row.id) return true;
      else if (!item.id && item.name === row.name) return true;
      return false;
    });
    findIndex > -1 && form.value.sdkLmKbFileTags.splice(findIndex, 1);
  }

  function handleSetFileInfo({ res, file }) {
    console.log({ res, file, form: form.value });
    // form.value.path = res.fileName;
    if (!form.value.name) {
      form.value.name = res.newFileName; //originalFilename
    }
    form.value.fileType = res.originalFilename.split('.')[1];
  }

  function handleTagClick() {}

  function reset() {
    form.value = {
      id: null,
      industryId: props.cateKb.industryId,
      catId: props.cateKb.catId,
      kbId: props.cateKb.id,
      name: null,
      fileType: null,
      type: null,
      path: null,
      del: null,
      sortValue: null,
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
      sdkLmKbFileTags: [],
      fileName: null,
    };
    sdkLmKbFileTagVal.value = '';
    formRef.value?.resetFields();
  }

  function handleQuery() {
    pageParams.value.pageNum = 1;
    getList();
  }

  function resetQuery() {
    queryRef.value?.resetFields();
    handleQuery();
  }

  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
  }

  function handleAdd() {
    reset();
    title.value = '添加知识库文件';
    open.value = true;
  }

  function handleUpdate(row) {
    reset();
    const _id = row?.id ?? ids.value[0];
    getSdkLmKbFileInfo(_id).then((res) => {
      form.value = res.data;
      title.value = '修改知识库文件';
      open.value = true;
    });
  }

  function handleDownload(row) {
    // axios({
    //   method: 'get',
    //   url: row.path,
    //   // responseType: 'blob',
    //   headers: { Authorization: 'Bearer ' + getToken() },
    // }).then((res) => {
    //   console.log({ res });
    // });

    downloadSdkLmKbFile({ id: row.id, fileName: row.name.split('.')[0] + '.' + row.fileType }).then(
      (res) => {
        console.log({ res });
      },
    );
  }

  function submitForm() {
    formRef.value.validate((valid) => {
      if (valid) {
        console.log({ form: form.value });
        if (form.value.id) {
          updateSdkLmKbFile(form.value).then(() => {
            modal.msgSuccess('修改成功');
            open.value = false;
            getList();
          });
        } else {
          addSdkLmKbFile(form.value).then(() => {
            modal.msgSuccess('新增成功');
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  function handleDelete(row) {
    const _ids = row?.id ?? ids.value.join(',');
    modal
      .confirm('是否确认删除知识库文件编号为"' + _ids + '"的数据项？')
      .then(() => {
        return delSdkLmKbFile(_ids);
      })
      .then(() => {
        getList();
        modal.msgSuccess('删除成功');
      })
      .catch(() => {});
  }

  // function handleExport() {
  //   exportSdkLmKbFile(pageParams.value, queryParams.value);
  // }

  // function handleImport() {
  //   upload.value.title = '知识库文件导入';
  //   upload.value.open = true;
  // }

  function importTemplate() {
    tplSdkLmKbFile();
  }

  function handleFileUploadProgress() {
    upload.value.isUploading = true;
  }

  function handleFileSuccess(res, file) {
    upload.value.open = false;
    upload.value.isUploading = false;
    uploadRef.value.handleRemove(file);
    modal.msgSuccess(res.msg);
    console.log({ res });
    getList();
  }

  function submitFileForm() {
    uploadRef.value.submit();
  }

  // getList();
</script>

<style lang="scss" scoped>
  .texthoveColor {
    color: #51a6ff;
    cursor: pointer;
    // &:hover {
    //   color: #51a6ff;
    // }
  }
</style>
